package com.yh.csx.crm.core.util;

import com.yh.csx.crm.core.exception.BusinessException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author Huang Zhaoping
 * @date 2019/4/22
 */
public class DownloadUtils {

    public static void download(HttpServletRequest request, HttpServletResponse response, String path) {
        File file = new File(path);
        try (InputStream input = file.exists() ? new FileInputStream(file) : Thread.currentThread().getContextClassLoader().getResourceAsStream(path)) {
            if (input == null) throw new FileNotFoundException();
            OutputStream output = getOutputStream(request, response, path);
            byte[] buff = new byte[1024];
            int bytesRead;
            while (-1 != (bytesRead = input.read(buff, 0, buff.length))) {
                output.write(buff, 0, bytesRead);
            }
            output.close();
            response.flushBuffer();
        } catch (FileNotFoundException e) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            throw new BusinessException("文件不存在: " + path);
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw new BusinessException("文件传输异常: " + e.getMessage(), e);
        }

    }

    public static Browser getBrowser(HttpServletRequest request) {
        String userAgent = request.getHeader("USER-AGENT").toLowerCase();
        if (userAgent != null) {
            if (userAgent.indexOf("msie") >= 0)
                return Browser.IE;
            if (userAgent.indexOf("firefox") >= 0)
                return Browser.FIREFOX;
            if (userAgent.indexOf("safari") >= 0)
                return Browser.SAFARI;
        }
        return null;
    }

    private static OutputStream getOutputStream(HttpServletRequest request, HttpServletResponse response, String filePath) throws IOException {
        String fileNameDisplay = new File(filePath).getName();
        try {
            fileNameDisplay = URLEncoder.encode(fileNameDisplay, "UTF-8");
            if (Browser.FIREFOX.equals(getBrowser(request))) {
                // 针对火狐浏览器处理方式不一样了
                fileNameDisplay = new String(fileNameDisplay.getBytes("UTF-8"), "iso-8859-1");
            }
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException("字符编码不支持");
        }

        response.setHeader("Content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileNameDisplay);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        return response.getOutputStream();
    }

    public enum Browser {
        IE,
        FIREFOX,
        SAFARI,;
    }
}
